import React, { useState } from 'react';
import { Card, Form, Input, Button, Checkbox, message, Row, Col } from 'antd';
import { UserOutlined, LockOutlined } from '@ant-design/icons';
import { Navigate } from 'react-router-dom';
import request from '../../../utils/request.jsx';

const LoginPage = () => {
  const [loading, setLoading] = useState(false);
  const [form] = Form.useForm();
  const [isAuthenticated, setIsAuthenticated] = useState(false);
  
  // 根据用户类型决定重定向目标
  if (isAuthenticated) {
    try {
      // 从localStorage获取用户信息
      const userInfoStr = localStorage.getItem('userInfo');
      if (userInfoStr) {
        const userInfo = JSON.parse(userInfoStr);
        // 检查用户是否是管理员
        if (userInfo.roles && userInfo.roles.includes('admin')) {
          return <Navigate to="/user" replace />; // 管理员跳转到用户管理页面
        }
      }
    } catch (error) {
      console.error('解析用户信息失败:', error);
    }
    return <Navigate to="/api" replace />; // 非管理员默认跳转到接口管理页面
  }
  
  // 处理登录表单提交
  const handleSubmit = async (values) => {
    try {
      setLoading(true);
      const response = await request.post('/auth-center/auth/login', values);
      if (response.code === 200) {
        // 保存token到localStorage
        if (response.token) {
          localStorage.setItem('token', response.token);
          localStorage.setItem('userInfo', JSON.stringify(response.userInfo || {}));
        }
        message.success('登录成功');
        // 登录成功后设置认证状态为true，这会触发重定向
        setIsAuthenticated(true);
      } else {
        message.error(response.message || '登录失败');
      }
    } catch (error) {
      message.error('登录失败，请检查网络或用户名密码');
      console.error('登录错误:', error);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="login-container">
      <Row justify="center" align="middle" className="login-row">
        <Col xs={24} sm={20} md={12} lg={8} xl={6}>
          <Card title="API管理平台登录" className="login-card">
            <Form
              form={form}
              layout="vertical"
              onFinish={handleSubmit}
              initialValues={{
                remember: true,
              }}
            >
              <Form.Item
                name="username"
                label="用户名"
                rules={[
                  { required: true, message: '请输入用户名' },
                  { whitespace: true, message: '用户名不能包含空格' },
                ]}
              >
                <Input
                  prefix={<UserOutlined className="site-form-item-icon" />}
                  placeholder="请输入用户名"
                  autoComplete="username"
                />
              </Form.Item>
              
              <Form.Item
                name="password"
                label="密码"
                rules={[
                  { required: true, message: '请输入密码' },
                ]}
              >
                <Input
                  prefix={<LockOutlined className="site-form-item-icon" />}
                  type="password"
                  placeholder="请输入密码"
                  autoComplete="current-password"
                />
              </Form.Item>
              
              <Form.Item>
                <Row justify="space-between" align="middle">
                  <Form.Item name="remember" valuePropName="checked" noStyle>
                    <Checkbox>记住我</Checkbox>
                  </Form.Item>
                  <div>
                    <Button type="link">忘记密码？</Button>
                    <Button type="link" onClick={() => window.location.href='/register'}>立即注册</Button>
                  </div>
                </Row>
              </Form.Item>
              
              <Form.Item>
                <Button
                  type="primary"
                  htmlType="submit"
                  className="login-button"
                  loading={loading}
                  block
                >
                  登录
                </Button>
              </Form.Item>
            </Form>
          </Card>
        </Col>
      </Row>
    </div>
  );
}

export default LoginPage;